<template>
  <div class="file_wrapper">
    <!--  image -->
    <template v-if="uri || fileId">
      <el-image
        ref="media"
        v-if="isImg"
        :src="src"
        :preview-src-list="previewList"
        fit="cover"
      />
      <i style="font-size: 36px" v-else class="el-icon el-icon-document"></i>
    </template>
    <template v-if="!uri && fileUrl">
      <el-image
        ref="media"
        v-if="isImg"
        :src="fileUrl"
        :preview-src-list="previewList"
        fit="cover"
      />
      <i style="font-size: 36px" v-else class="el-icon el-icon-document"> </i>
    </template>
  </div>
</template>

<script>
export default {
  props: {
    uri: {
      type: String,
    },
    fileUrl: {
      type: String,
    },
    fileType: {
      type: String,
    },
    remote: {
      type: Object,
      default: () => ({}),
    },
    fileId: {
      type: String,
    },
  },
  data() {
    return {
      src: '',
    }
  },
  created() {
    if (this.fileId) {
      this.getUrl({ type: 'fileId', keys: this.fileId })
    } else if (this.uri) {
      this.getUrl({ type: 'uri', keys: this.uri })
    }
  },
  watch: {
    uri(val, oldVal) {
      if (val !== oldVal && val) {
        this.getUrl({ type: 'uri', keys: val })
      }
    },
    fileId(val, oldVal) {
      if (val !== oldVal && val) {
        this.getUrl({ type: 'fileId', keys: val })
      }
    },
  },
  computed: {
    isImg() {
      const type = this.fileType
      return (
        type === 'png' ||
        type === 'jpg' ||
        type === 'jpeg' ||
        type === 'gif' ||
        !type
      )
    },
    previewList() {
      return [this.src]
    },
  },
  methods: {
    getUrl(params) {
      if (
        this.remote &&
        this.remote['$getFileUrl'] &&
        typeof this.remote['$getFileUrl'] == 'function'
      ) {
        this.remote['$getFileUrl'](params).then((src) => {
          this.src = src
        })
      }
    },
    handlePreview() {
      if (this.isImg) {
        this.$refs.media.clickHandler()
      } else {
        this.window.open(this.src)
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.file_wrapper {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
